<template>
  <div class="container" @viewappear="onViewappear">
    <template v-if="loaded">
      <navbar fixed="true" title="商品详情" theme="transparent"
              :showTitle="scrollOffsetY < 0"
              rightItemIcon="true"
              :rightHidden="true"
              @rightItemClick="share"
              :scrollOffsetY="scrollOffsetY">
        <template slot="rightItemIcon">&#xe608;</template>
      </navbar>
      <list @scroll="onPageScroll">
        <page-refresh v-on:refresh="onXRefresh" v-on:pullingDown="onPullingDown" :refreshing="refreshing"
                      :indicatorScale="indicatorScale"></page-refresh>
        <cell>
          <slider ref="topNode" class="item-img-slider" interval="3000" auto-play="true">
            <div v-for="img in item.itemImgs" class="item-pic" v-bind:key="img">
              <image resize="cover" class="item-pic" :src="img"></image>
            </div>
            <indicator class="item-img-slider-indicator"></indicator>
          </slider>
        </cell>
        <cell>
          <div class="panel bg-white">
            <text class="item-intro" v-if="item.description">{{item.description}}</text>
            <div class="panel-body">
              <div class="item-title">
                <image :src="item.$_platformIcon" class="item-title-icon"></image>
                <text class="item-title-text">      {{item.jdSale ? '【自营】' : (item.freeShipment ? '【包邮】' : '')}}{{item.title}}</text>
              </div>
              <div class="item-detail-row">
                <div class="item-price">
                  <text class="item-price-y">¥</text>
                  <text class="item-price-val">{{item.price.toFixed(1)}}</text>
                  <text class="item-price-origin-val">¥{{item.originPrice}}</text>
                </div>
                <div class="sales">
                  <text class="sales-title">销量</text>
                  <text class="sales-val" v-if="item.sales !==  -1"> {{item.sales}}</text>
                  <text class="sales-val" v-if="item.sales == -1"> 预售</text>
                </div>
                <coupon :couponValue="item.couponValue" size="md" v-if="item.coupon"></coupon>
              </div>
            </div>
            <div class="panel-body item-detail-row bg-muted">
              <x-image v-if="freeChargeActivityMarkIcon" :height="30" @click="freeChargeActivityMarIconClick" :src="freeChargeActivityMarkIcon"></x-image>
              <div class="item-share-info" v-if="iosShow">
                <text class="item-share-info-title">自购省</text>
                <text class="item-share-info-y"> ¥</text>
                <text class="item-share-info-value">{{(item.shareCommission).toFixed(2)}}</text>
                <text class="item-share-info-value text-info">+{{(item.rewardShareCommission).toFixed(2)}}</text>
              </div>
              <text class="shop-title text-muted">{{item.shopTitle}}</text>
            </div>
          </div>
        </cell>
        <header>
          <div class="item-desc-cell" @click="descBtnClick">
            <text class="item-desc-title">商品详情</text>
            <text class="item-desc-arrow icon">{{showDesc ? '\ue661' : '\ue601'}}</text>
          </div>
        </header>
        <cell v-if="showDesc">
          <x-image :src="img.src" v-for="(img, idx) in descImgList" v-bind:key="idx" :width="750"></x-image>
        </cell>
        <header>
          <div class="floor-heading bg-white">
            <div class="floor-heading-line-through"></div>
            <text class="floor-heading-title text-primary">为你推荐</text>
            <div class="floor-heading-line-through"></div>
          </div>
        </header>
        <template v-if="sameStyleList.length" v-for="(itemList, rowIdx) in sameStyleRowList">
          <item-cell @commissionItemClick="commissionItemClick" :itemList="itemList" v-bind:key="rowIdx"></item-cell>
        </template>
        <cell>
          <page-notice msg="抱歉，什么都木有找到～" :icon="sorryIcon" v-if="!sameStyleList.length"></page-notice>
        </cell>
      </list>
      <div class="footerbar">
        <text :class="['icon', 'footerbar-btn', 'activeable', 'footerbar-btn-favor']" v-if="!favor"
              @click="toggleFavor">&#xe64c;
        </text>
        <text :class="['icon', 'footerbar-btn', 'activeable', 'footerbar-btn-favor', 'favor-highlight']" v-if="favor"
              @click="toggleFavor">&#xe64b;
        </text>
        <div class="footerbar-btn share-btn activeable footerbar-btn-flex" @click="share" v-if="iosShow">
          <text class="footerbar-btn-icon icon">&#xe608;</text>
          <text class="footerbar-btn-text share-btn-text"> 分享赚钱</text>
        </div>
        <div class="footerbar-btn buy-btn activeable footerbar-btn-flex" @click="goToBuy" v-if="flashSaleRemainSeconds <= 0 && !freeChargeActivityId">
          <text class="footerbar-btn-text share-btn-text" v-if="item.sales !==  -1"> {{item.coupon ? '领券 ¥' + item.couponValue : '立即购买'}}</text>
          <text class="footerbar-btn-text share-btn-text" v-if="item.sales == -1"> 预售抢购</text>
        </div>
        <div class="footerbar-btn fee-buy-btn activeable footerbar-btn-flex" v-if="freeChargeActivityId" @click="freeChargeBuy()">
          <text class="footerbar-btn-icon icon">&#xe62c;</text>
          <text class="footerbar-btn-text share-btn-text"> {{freeChargeActivityBtnTitle}}</text>
        </div>
        <div v-if="flashSaleRemainSeconds > 0" :class="['footerbar-btn', 'buy-btn', 'btn-locked']" @click="fillTradeNo">
          <text :class="['icon', 'footerbar-btn-icon', 'text-locked']">&#xe633;</text>
          <text :class="['footerbar-btn-text', 'text-locked']"> 即将开抢</text>
        </div>
      </div>
      <page-scrolltop :shown="pageScrollTopShown" @click="gotoTop" :bottom="130"></page-scrolltop>
    </template>
    <page-loading :loaded="loaded"></page-loading>
    <wxc-loading :show="loadingShow"></wxc-loading>
    <free-charge-activity ref="freeChargeActivity" @draw="freeChargeActivityDraw"></free-charge-activity>
  </div>
</template>
<script>
import {WxcPopup, WxcLoading} from 'weex-ui'
let navigator = require('./include/xnavigator')
let queryparser = require('./include/queryparser')
let api = require('./include/api')
let grouping = require('./include/grouping')
let urlPath = require('./include/url-path')
let config = require('./include/app-config')
let pageCache = require('./include/page-cache')
let PAGE_DATE_CACHE = 'PAGE_COMMISSION_ITEM_DATA'
let commissionItemTools = require('./include/commission-item-tools')
module.exports = {
  mixins: [
    require('./mixin/page-refresh'),
    require('./mixin/page-scrolltop'),
    require('./mixin/page-loading')
  ],
  components: {
    navbar: require('./components/navbar.vue'),
    coupon: require('./components/coupon.vue'),
    'item-cell': require('./components/commission-item-cell.vue'),
    'x-image': require('./components/x-image.vue'),
    'free-charge-activity': require('./components/free-charge-activity-draw.vue'),
    WxcPopup,
    WxcLoading
  },
  data () {
    return {
      iosShow: false,
      refreshing: false,
      refreshIndicatorScale: 0.2,
      item: {},
      sameStyleList: [],
      sameStyleRowList: [],
      id: 0,
      sourceItemId: 0,
      sorryIcon: urlPath.assets('images/aiya.png'),
      scrollOffsetY: 0,
      favor: false,
      descShow: false,
      descHeight: 0,
      descImgList: [],
      descUrl: '',
      flashSaleRemainSeconds: 0,
      showDesc: false,
      loadingShow: false,
      freeChargeActivityId: '',
      freeChargeActivityName: '',
      freeChargeActivityMarkIcon: ''
    }
  },
  destroyed () {

  },
  created () {
    config.bindConfig(this)
    let cfg = weex.config
    let param = queryparser(cfg.bundleUrl)
    this.id = param.id || ''
    this.freeChargeActivityId = param.freeChargeActivityId || ''
    this.PAGE_DATE_CACHE = PAGE_DATE_CACHE + '@' + this.id
    this.PAGE_DESC_DATE_CACHE = PAGE_DATE_CACHE + '_DESC@' + this.id
    this.PAGE_SAME_STYLE_DATE_CACHE = PAGE_DATE_CACHE + '_SAME_STYLE@' + this.id
    if (param.flashSaleRemainSeconds) {
      this.flashSaleRemainSeconds = parseInt(param.flashSaleRemainSeconds)
    }
    this.sourceItemId = param.sourceItemId || ''
    this.ecomPlat = param.ecomPlat || ''
    if (this.sourceItemId) {
      this.PAGE_DATE_CACHE = PAGE_DATE_CACHE + '@' + this.sourceItemId + '_' + this.ecomPlat
      this.PAGE_DESC_DATE_CACHE = PAGE_DATE_CACHE + '_DESC@' + this.sourceItemId + '_' + this.ecomPlat
      this.PAGE_SAME_STYLE_DATE_CACHE = PAGE_DATE_CACHE + '_SAME_STYLE@' + this.sourceItemId + '_' + this.ecomPlat
    }
    pageCache.cache(this.PAGE_DATE_CACHE).done(rs => {
      if (rs) {
        this.handleData(rs)
        this.loaded = true
      } else {
        this.loadData().done(rs => {
          this.loaded = true
        })
      }
    })
    pageCache.cache(this.PAGE_DESC_DATE_CACHE).done(rs => {
      if (rs) {
        this.handleDescData(rs)
      } else {
        this.loadDesc()
      }
    })
    pageCache.cache(this.PAGE_SAME_STYLE_DATE_CACHE).done(rs => {
      if (rs) {
        this.handleSameStyle(rs)
      } else {
        this.findSameStyle()
      }
    })
  },
  methods: {
    loadData () {
      return api.page.commissionItem.data({
        id: this.id,
        ecomPlat: this.ecomPlat,
        sourceItemId: this.sourceItemId,
        freeChargeActivityId: this.freeChargeActivityId
      }).done(rs => {
        pageCache.cache(this.PAGE_DATE_CACHE, rs)
        this.handleData(rs)
      })
    },
    handleData (rs) {
      let data = rs.data
      this.favor = data.favor
      this.item = data.commissionItem
      this.freeChargeActivityMarkIcon = data.freeChargeActivityMarkIcon
      this.freeChargeActivityBtnTitle = data.freeChargeActivityBtnTitle
      this.freeChargeActivityHelpUrl = data.freeChargeActivityHelpUrl
      this.freeChargeActivityName = data.freeChargeActivityName
      // modal.alert({message: JSON.stringify(this.item)})
      this.id = this.item.id || ''
      this.loadDesc()
      this.item.$_platformIcon = urlPath.assets('images/icon/platform/' + this.item.ecomPlat + '.png')
    },
    loadDesc () {
      api.item.descImgList({id: this.id}).done(rs => {
        pageCache.cache(this.PAGE_DESC_DATE_CACHE, rs)
        this.handleDescData(rs)
        this.showDesc = true
      })
    },
    handleDescData (rs) {
      let imgs = rs.data
      this.descImgList = imgs.map(img => {
        return {
          src: img,
          width: 10,
          height: 10
        }
      })
    },
    onViewappear() {
      this.loadingShow = false
    },
    descBtnClick () {
      this.showDesc = !this.showDesc
    },
    descOverlayClick () {
      this.descShow = false
    },
    favorClick () {
      this.favor = !this.favor
    },
    onXRefresh (event) {
      this.onRefresh(event, this.loadData(), this.findSameStyle())
    },
    toggleFavor () {
      api.footmark.toggleFavor({
        id: this.id
      }).done(rs => {
        let flag = rs.data
        if (flag) {
          this.favor = true
        } else {
          this.favor = false
        }
      })
    },
    gotoTop () {
      let dom = weex.requireModule('dom')
      dom.scrollToElement(this.$refs.topNode)
    },
    onPageScroll (event) {
      this.scrollOffsetY = event.contentOffset.y
      this.onPageScrollForScrollTop(event)
    },
    findSameStyle () {
      return api.search.commissionItemSameStyle({id: this.id || 0}).done(rs => {
        pageCache.cache(this.PAGE_SAME_STYLE_DATE_CACHE, rs)
        this.handleSameStyle(rs)
      })
    },
    handleSameStyle (rs) {
      this.sameStyleList = rs.data
      this.sameStyleRowList = grouping(this.sameStyleList, 2, {})
    },
    commissionItemClick (item) {
      navigator.push('commission-item.js?id=' + item.id, () => {

      })
    },
    goToBuy () {
      let self = this
      commissionItemTools.goToBuy(this.id, {
        onRequest () {
          self.loadingShow = true
        }
      }).always(() => {
        this.loadingShow = false
      })
    },
    freeChargeActivityMarIconClick () {
      navigator.push({
        url: 'webpage.js?url=' + encodeURIComponent(this.freeChargeActivityHelpUrl) + '&title=' + encodeURIComponent(this.freeChargeActivityName)
      })
    },
    share () {
      commissionItemTools.share(this.id, this.item.ecomPlat)
    },
    freeChargeActivityDraw (success) {
      success && this.goToBuy()
    },
    freeChargeBuy () {
      this.$refs.freeChargeActivity.show({
        itemId: this.id,
        freeChargeActivityId: this.freeChargeActivityId
      })
    }
  }
}
</script>
<style lang="scss">
  @import "./sass/var";
  @import "./sass/icon";
  @import "./sass/floor";
  @import "./sass/utilities";
  @import "./sass/activeable";

  $padding-v: 20px;
  .container {
    background-color: $body-bg;
  }

  .btn-locked {
    background-color: #979797;
  }

  .shop-info {
    background-color: #FFFFFF;
    @include border-bottom(1px, solid, #ddd);
    padding: 20px;
  }

  .item-desc {
    &-cell {
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      height: 70px;
      background-color: #FFFFFF;
      margin: 0 0 10px 0;
      padding: 0 20px;
    }
    &-title {
      font-size: 28px;
      color: $color;
      font-weight: 300;
    }
    &-arrow {
      font-size: 28px;
      color: $color-muted;
    }
  }

  .desc-title {
    padding: 10px;
    text-align: center;
    font-size: 32px;
    color: $color;
    @include border-bottom(1px, solid, #ddd);
    background-color: #efefef;
  }

  .footerbar {
    $height: 96px;
    background-color: #ffffff;
    flex-direction: row;
    justify-content: space-between;
    align-items: stretch;
    height: $height;
    box-shadow: 0 0 5px #bfbfbf;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    &-btn {
      justify-content: center;
      flex-direction: row;
      align-items: center;
      &-icon {
        font-size: 40px;
        color: #ffffff;
      }
      &-flex {
        flex: 1;
      }
      &-favor {
        width: $height;
        height: $height;
        font-size: 60px;
        text-align: center;
        line-height: $height;
        color: $color-muted;
      }
      &-text {
        font-size: 32px;
        line-height: 32px;
        height: 32px;
        color: #ffffff;
      }
      &-price {
        margin-top: 5px;
        font-size: 24px;
        line-height: 24px;
        height: 24px;
        color: #ffffff;
      }
    }
  }

  .share-btn {
    background-color: #ff9835;
  }

  .buy-btn {
    background-color: $brand-primary;
  }

  .fee-buy-btn {
    background-color: #fb0095;
  }

  .bg-white {
    background-color: #ffffff;
  }

  .bg-muted {
    background-color: #FAFAFA;
  }

  .panel {
    margin-bottom: 10px;
    margin-top: 10px;
    &-body {
      padding: 20px;
    }
  }

  .favor-highlight {
    color: $color-primary;
  }

  .item-pic {
    width: 750px;
    height: 750px;
  }

  .item-img-slider {
    position: relative;
    height: 750px;
    width: 750px;
    &-indicator {
      height: 30px;
      item-color: white;
      item-selected-color: $color-primary;
      item-size: 15px;
      position: absolute;
      bottom: 10px;
      left: 0;
      right: 0
    }

  }

  .shop-title {
    color: #666;
    font-size: 28px;
    text-align: right;
    &-dp {
      font-size: 28px;
      color: $color-muted;
    }
  }
  .item {
    &-intro {
      padding: 20px;
      background-color: $color-primary;
      font-size: 30px;
      color: #fff;
    }
  }
  .item-title {
    position: relative;
    margin-bottom: 20px;
    &-text {
      font-size: 32px;
      color: #000;
      line-height: 40px;
      lines: 2;
      text-overflow: ellipsis;
    }

    &-icon {
      width: 40px;
      height: 40px;
      position: absolute;
      top: 0;
      left: 0;
    }
  }

  .item-detail-row {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }

  .item-price {
    flex-direction: row;
    align-items: flex-end;
    &-y {
      font-size: 28px;
      color: $color-primary;
      line-height: 28px;
    }
    &-val {
      font-size: 44px;
      line-height: 44px;
      height: 44px;
      color: $color-primary;
    }
    &-origin {
      &-y {
        font-size: 24px;
        text-decoration: line-through;
        margin-left: 30px;
        color: $color-muted;
      }
      &-val {
        margin-left: 20px;
        font-size: 28px;
        text-decoration: line-through;
        color: $color-muted;
      }
    }
  }

  .item-plus-share-info {
    flex-direction: row;
    align-items: flex-end;
    &-title {
      font-size: 24px;
      color: $color-warning;
      font-weight: 100;
    }
    &-y {
      font-size: 28px;
      color: $color-warning;
    }
    &-value {
      font-size: 28px;
      color: $color-warning;
    }
  }

  .item-share-info {
    flex-direction: row;
    align-items: flex-end;
    &-title {
      font-size: 24px;
      color: #454545;
      font-weight: 100;
    }
    &-y {
      font-size: 28px;
      color: #454545;
    }
    &-value {
      font-size: 28px;
      color: #454545;
    }
  }

  .sales {
    flex-direction: row;
    align-items: flex-end;
    &-title {
      font-size: 24px;
      color: $color-muted;
      font-weight: 100;
    }
    &-val {
      font-size: 28px;
      color: $color-muted;
    }
  }
</style>
